from rest_framework import viewsets, permissions
from rest_framework.response import Response
from rest_framework.decorators import action
from django.shortcuts import get_object_or_404

from rest_framework import serializers
from .models import *
from .serializers import *

import base64
from django.core.files.base import ContentFile

class UserOwnedModelViewSet(viewsets.ModelViewSet):
    """
    A base viewset for user-owned models.
    """
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        return self.queryset.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

class CategoryViewSet(UserOwnedModelViewSet):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

class SubCategoryViewSet(viewsets.ModelViewSet):
    queryset = SubCategory.objects.all()
    serializer_class = SubCategorySerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # Filter subcategories by the user's categories
        return self.queryset.filter(parent__user=self.request.user)

class ColorViewSet(UserOwnedModelViewSet):
    queryset = Color.objects.all()
    serializer_class = ColorSerializer

class SeasonViewSet(viewsets.ModelViewSet):
    queryset = Season.objects.all()
    serializer_class = SeasonSerializer
    
class ThicknessViewSet(UserOwnedModelViewSet):
    queryset = Thickness.objects.all()
    serializer_class = ThicknessSerializer

class StorageLocationViewSet(UserOwnedModelViewSet):
    queryset = StorageLocation.objects.all()
    serializer_class = StorageLocationSerializer

class BrandViewSet(UserOwnedModelViewSet):
    queryset = Brand.objects.all()
    serializer_class = BrandSerializer

class SizeTypeViewSet(UserOwnedModelViewSet):
    queryset = SizeType.objects.all()
    serializer_class = SizeTypeSerializer

class SizeViewSet(viewsets.ModelViewSet):
    queryset = Size.objects.all()
    serializer_class = SizeSerializer

class MaterialViewSet(UserOwnedModelViewSet):
    queryset = Material.objects.all()
    serializer_class = MaterialSerializer

class TagTypeViewSet(UserOwnedModelViewSet):
    queryset = TagType.objects.all()
    serializer_class = TagTypeSerializer

class TagViewSet(viewsets.ModelViewSet):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    permission_classes = [permissions.IsAuthenticated]

    def get_queryset(self):
        # Filter tags by the user's tag types
        return self.queryset.filter(parent__user=self.request.user)

class ImageViewSet(viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer
    permission_classes = [permissions.IsAuthenticated]

class ClothesViewSet(UserOwnedModelViewSet):
    queryset = Clothes.objects.all()
    serializer_class = ClothesSerializer

    # 上传图片的接口
    # 修改为，通过文件名称、base64的文件内容上传图片
    @action(detail=True, methods=['post'], url_path='update_main_image')
    def update_main_image(self, request, pk=None):
        clothes = self.get_object()
        serializer = self.get_serializer(clothes, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)

        if 'file_name' in request.data and 'base64_content' in request.data:
            file_name = request.data['file_name']
            base64_content = request.data['base64_content']

            # 移除Base64编码的前缀
            if base64_content.startswith('data:'):
                base64_content = base64_content.split(',', 1)[1]

            # 解码Base64内容
            decoded_content = base64.b64decode(base64_content)

            # 创建ContentFile对象
            content_file = ContentFile(decoded_content, name=file_name)

            # 更新主图
            clothes.main_image = content_file
            clothes.save()

        return Response(serializer.data)

class ClothesMaterialViewSet(viewsets.ModelViewSet):
    queryset = ClothesMaterial.objects.all()
    serializer_class = ClothesMaterialSerializer

class SuitsViewSet(UserOwnedModelViewSet):
    queryset = Suits.objects.all()
    serializer_class = SuitsSerializer

class LocationInfoViewSet(viewsets.ModelViewSet):
    queryset = LocationInfo.objects.all()
    serializer_class = LocationInfoSerializer
    permission_classes = [permissions.IsAuthenticated]

class WeatherConditionViewSet(viewsets.ModelViewSet):
    queryset = WeatherCondition.objects.all()
    serializer_class = WeatherConditionSerializer
    permission_classes = [permissions.IsAuthenticated]

class FeelingViewSet(viewsets.ModelViewSet):
    queryset = Feeling.objects.all()
    serializer_class = FeelingSerializer
    permission_classes = [permissions.IsAuthenticated]

class RecordViewSet(UserOwnedModelViewSet): 
    queryset = Record.objects.all()
    serializer_class = RecordSerializer
    
    def perform_create(self, serializer):
        # 自动将 user 设置为当前登录用户
        serializer.save(user=self.request.user)